var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var at_type = $("#at_type").val();
var allot_up = $("#allot_up").val();
var _limitMenu = '';
if(at_type == '0'){//配货
	if(system.SHOP_TYPE == 1){//总公司--配货发货单
		_limitMenu = system.MENULIMIT.SORT02;
	}else if(system.SHOP_TYPE == 2){//分公司
		if(allot_up == 0){//配货发货单
			_limitMenu = system.MENULIMIT.SORT02;
		}else{//配货申请单
			_limitMenu = system.MENULIMIT.SORT01;
		}
	}else{//加盟店、合伙店--配货申请单
		_limitMenu = system.MENULIMIT.SORT01;
	}
}else if(at_type == '1'){//退货
	if(system.SHOP_TYPE == 1){//总公司--退货确认单
		_limitMenu = system.MENULIMIT.SORT04;
	}else if(system.SHOP_TYPE == 2){//分公司
		if(allot_up == 0){//退货确认单
			_limitMenu = system.MENULIMIT.SORT04;
		}else{//退货申请单
			_limitMenu = system.MENULIMIT.SORT03;
		}
	}else{//加盟店、合伙店--退货申请单
		_limitMenu = system.MENULIMIT.SORT03;
	}
}
var _menuParam = config.OPTIONLIMIT;
var queryurl = config.BASEPATH+'sort/allot/page';

var Utils = {
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择配货门店',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:false,module:'allot'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#at_shop_code").val(selected.sp_code);
				$("#shop_name").val(selected.sp_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#at_shop_code").val(selected.sp_code);
					$("#shop_name").val(selected.sp_name);
				}
			},
			cancel:true
		});
	},
	doQueryDepot : function(code,name){
		commonDia = $.dialog({
			title : '选择仓库',
			content : 'url:'+config.BASEPATH+'base/depot/to_list_dialog_bymodule',
			data : {multiselect:false,module:'allot'},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#"+code).val(selected.dp_code);
				$("#"+name).val(selected.dp_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#"+code).val(selected.dp_code);
					$("#"+name).val(selected.dp_name);
				}
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#at_manager").val(selected.em_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#at_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	operate: function(oper, id){//修改、新增
		if(oper == 'add'){
			url = config.BASEPATH+"sort/allot/to_add/"+at_type+"/"+allot_up;
			data = {oper: oper, callback:this.callback};
		}else if(oper == 'edit'){
			url = config.BASEPATH+"sort/allot/to_update/"+allot_up+"?at_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'view'){
			url = config.BASEPATH+"sort/allot/to_view?at_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'approve'){
			url = config.BASEPATH+"sort/allot/to_view?at_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'send'){
			url = config.BASEPATH+"sort/allot/to_send/"+allot_up+"?at_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'receive'){
			url = config.BASEPATH+"sort/allot/to_view?oper=receive&at_id="+id;
			data = {oper: oper,callback: this.callback};
		}else if(oper == 'rejectconfirm'){
			url = config.BASEPATH+"sort/allot/to_view?at_id="+id;
			data = {oper: oper,callback: this.callback};
		}else{
			return false;
		}
		$.dialog({
			title : false,
			content : 'url:'+url,
			data: data,
			max : false,
			min : false,
			cache : false,
			lock: false
		}).max();
	},
	del: function(rowId){//删除
		var rowData = $("#grid").jqGrid("getRowData", rowId);
	 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'sort/allot/del',
				data:{"number":rowData.at_number},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : '删除成功!'});
						$('#grid').jqGrid('delRowData', rowId);
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		});	
    },
    callback: function(data, oper, dialogWin){
    	if(oper == "edit") {
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
		if(oper == "approve") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "send") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "receive") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "rejectconfirm") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "view") {
			$("#grid").jqGrid('setRowData', data.id, data);
			dialogWin && dialogWin.api.close();
		}
		if(oper == "add"){
			THISPAGE.reloadData();
			dialogWin && dialogWin.api.close();
		}
	},
	operFmatter : function(val, opt, row){
		var btnHtml = '';
		if (row.at_ar_state == '2'){//退回
			if(system.US_ID == row.at_us_id){
        		btnHtml += '<input type="button" value="修改" class="btn_xg" onclick="javascript:handle.operate(\'edit\',' + opt.rowId + ');" />';
        	}else{
        		alert(row.at_us_id)
        		btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
        	}
		}else if (row.at_ar_state == '4') {//完成
        	btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
        }else{
        	if(at_type == '0'){//配货
    			if(system.SHOP_TYPE == 1 || (system.SHOP_TYPE == 2 && allot_up == 0)){//总公司、分公司(发货单)
    				if (row.at_ar_state == '0') {
    					if(row.at_applyamount == 0){//配货发货单
    						btnHtml += '<input type="button" value="审核" class="btn_sp" onclick="javascript:handle.operate(\'approve\',' + opt.rowId + ');" />';
    					}else{//配货申请单
    						btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
    					}
    		        }else if (row.at_ar_state == '1') {//审核通过
    		        	btnHtml += '<input type="button" value="发货" class="btn_qh" onclick="javascript:handle.operate(\'send\',' + opt.rowId + ');" />';
    		        }else if (row.at_ar_state == '3') {
    		        	btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
    		        }else if (row.at_ar_state == '5') {
    		        	btnHtml += '<input type="button" value="确认" class="btn_xg" onclick="javascript:handle.operate(\'rejectconfirm\',' + opt.rowId + ');" />';
    		        } 
    			}else{//申请单
    				if (row.at_ar_state == '0') {
    					if(row.at_applyamount == 0){//配货发货单
    						btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
    					}else{//配货申请单
    						btnHtml += '<input type="button" value="审核" class="btn_sp" onclick="javascript:handle.operate(\'approve\',' + opt.rowId + ');" />';
    					}
    		        }else if (row.at_ar_state == '1') {//审核通过
    		        	btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
    		        }else if (row.at_ar_state == '3') {
    		        	btnHtml += '<input type="button" value="接收" class="btn_qh" onclick="javascript:handle.operate(\'receive\',' + opt.rowId + ');" />';
    		        }else if (row.at_ar_state == '5') {
    		        	btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
    		        } 
    			}
    		}else if(at_type == '1'){//退货
    			if (row.at_ar_state == '0') {
    				btnHtml += '<input type="button" value="审核" class="btn_sp" onclick="javascript:handle.operate(\'approve\',' + opt.rowId + ');" />';
    			}else{
    	        	if(system.SHOP_TYPE == 1 || (system.SHOP_TYPE == 2 && allot_up == 0)){//总公司、分公司(确认单)
    					if (row.at_ar_state == '1') {
    						btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
    					}else if (row.at_ar_state == '3') {
    						btnHtml += '<input type="button" value="接收" class="btn_qh" onclick="javascript:handle.operate(\'receive\',' + opt.rowId + ');" />';
    			        }else if (row.at_ar_state == '5') {
    			        	btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
    			        } 
    				}else{//申请单
    					if (row.at_ar_state == '1') {
    						btnHtml += '<input type="button" value="退货" class="btn_qh" onclick="javascript:handle.operate(\'send\',' + opt.rowId + ');" />';
    					}else if (row.at_ar_state == '3') {
    						btnHtml += '<input type="button" value="查看" class="btn_ck" onclick="javascript:handle.operate(\'view\',' + opt.rowId + ');" />';
    			        }else if (row.at_ar_state == '5') {
    			        	btnHtml += '<input type="button" value="确认" class="btn_xg" onclick="javascript:handle.operate(\'rejectconfirm\',' + opt.rowId + ');" />';
    			        }
    				}
    	        }
    		}
        }
		btnHtml += '<input type="button" value="流程" class="btn_qh" onclick="javascript:listBillProcess(\''+row.at_number+'\',\'t_sort_allot\');" />';
		return btnHtml;
	},
	formatArState:function(val, opt, row){//0：未审核；1：已审核2：已退回
		if(val == 0){
			return '未审核';
		}else if(val == 1){
			return '已审核';
		}else if(val == 2){
			return '已退回';
		}else if(val == 3){
			return '在途';
		}else if(val == 4){
			return '完成';
		}else if(val == 5){
			return '拒收';
		}
		return val;
	},
	formatGapAmount:function(val, opt, row){
		if(isNaN(row.at_applyamount)){
			return val;
		}
		return row.at_applyamount-row.at_sendamount;
	}
};
var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();	
	},
	initDom:function(){
		this.$_date = $("#date").cssRadio({ callback: function($_obj){
			dateRedioClick($_obj.find("input").attr("id"));
		}});
		dateRedioClick("theDate");
		this.$_ar_state = $("#ar_state").cssRadio({ callback: function($_obj){
			$("#at_ar_state").val($_obj.find("input").val());
		}});
	},
	gridTotal:function(){
    	var grid=$('#grid');
		var at_applyamount=grid.getCol('at_applyamount',false,'sum');
		var at_sendamount=grid.getCol('at_sendamount',false,'sum');
    	var at_applymoney=grid.getCol('at_applymoney',false,'sum');
    	var at_sendmoney=grid.getCol('at_sendmoney',false,'sum');
    	var at_sendsellmoney=grid.getCol('at_sendsellmoney',false,'sum');
    	var userData = $("#grid").getGridParam('userData');
    	grid.footerData('set',{at_number:'本页小计<br>总计',
    		at_applyamount:at_applyamount+"<br>"+userData.at_applyamount,
    		at_sendamount:at_sendamount+"<br>"+userData.at_sendamount,
    		sub_amount:(at_applyamount-at_sendamount)+"<br>"+(userData.at_applyamount-userData.at_sendamount),
    		at_applymoney:at_applymoney.toFixed(2)+"<br>"+userData.at_applymoney.toFixed(2),
    		at_sendmoney:at_sendmoney.toFixed(2)+"<br>"+userData.at_sendmoney.toFixed(2),
    		at_sendsellmoney:at_sendsellmoney.toFixed(2)+"<br>"+userData.at_sendsellmoney.toFixed(2)});
    },
	initGrid:function(){
		var gridWH = Public.setGrid();
		var colModel = [
	    	{name: 'operate',label:'操作',width: 100, formatter: handle.operFmatter,align:'center', sortable:false},
	    	{name: 'at_us_id',label:'',index: 'at_us_id',width:100,hidden:true},
	    	{name: 'at_number',label:'单据编号',index: 'at_number',width:150},
	    	{name: 'at_date',label:'日期',index: 'at_date',width:80},
	    	{name: 'shop_name',label:'店铺',index: 'at_shop_code',width:120},
	    	{name: 'outdepot_name',label:'发货仓库',index: 'at_outdp_code',width:120},
	    	{name: 'indepot_name',label:'收货仓库',index: 'at_indp_code',width:120},
	    	{name: 'at_ar_state',label:'状态',index: 'at_ar_state',width:80,formatter: handle.formatArState},
	    	{name: 'at_manager',label:'经办人',index: 'at_manager',width:100},
	    	{name: 'at_applyamount',label:'申请',index: 'at_applyamount',width:80,align:'right'},
	    	{name: 'at_sendamount',label:'实发',index: 'at_sendamount',width:80,align:'right'},
	    	{name: 'sub_amount',label:'相差',index: 'at_applyamount-at_sendamount',width:80,align:'right',formatter: handle.formatGapAmount},
	    	{name: 'at_applymoney',label:'申请金额',index: 'at_applymoney',width:80,align:'right',formatter: PriceLimit.formatByDistribute},
	    	{name: 'at_sendmoney',label:'实发金额',index: 'at_sendmoney',width:80,align:'right',formatter: PriceLimit.formatByDistribute},
	    	{name: 'at_sendsellmoney',label:'实发零售金额',index: 'at_sendsellmoney',width:80,align:'right',formatter: PriceLimit.formatBySell},
	    	{name: 'at_ar_date',label:'审核日期',index: 'at_ar_date',width:80},
	    	{name: 'at_maker',label:'制单人',index: 'at_maker',width:100},
	    	{name: 'at_remark',label:'备注',index: 'at_maker',width:150}
	    ];
		$('#grid').jqGrid({
            url:queryurl+'?'+THISPAGE.buildParams(),			
			datatype: 'json',
			width: gridWH.w-12,
			height: gridWH.h-90,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:true,
			recordtext:'{0} - {1} 共 {2} 条',  
			multiselect:false,//多选
			viewrecords: true,
			rowNum:config.BASEROWNUM,//每页条数
			rowList:config.BASEROWLIST,//分页条数
			cmTemplate: {sortable:true,title:false},
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			userDataOnFooter: true,
			jsonReader: {
				root: 'data.list',
				total: 'data.pageInfo.totalPage',
                page: 'data.pageInfo.currentPage',
                records: 'data.pageInfo.totalRow',
                userdata: 'data.data',
				repeatitems : false,
				id: 'at_id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.gridTotal();
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	buildParams : function(){
		var params = '';
		params += 'at_type='+at_type;
		params += '&allot_up='+allot_up;
		params += '&at_isdraft=0';
		params += '&at_ar_state='+$("#at_ar_state").val();
		params += '&begindate='+$("#begindate").val();
		var enddate = $("#enddate").val();
		if(enddate != ""){
			params += '&enddate='+enddate+' 23:59:59';
		}else{
			params += '&enddate='+$("#enddate").val();
		}
		params += '&at_shop_code='+$("#at_shop_code").val();
		params += '&at_outdp_code='+$("#at_outdp_code").val();
		params += '&at_indp_code='+$("#at_indp_code").val();
		params += '&at_manager='+Public.encodeURI($("#at_manager").val());
		params += '&at_number='+Public.encodeURI($("#at_number").val());
		params += '&fromJsp='+$.trim($("#fromJsp").val());
		return params;
	},
	reset:function(){
		$("#at_shop_code").val("");
		$("#at_outdp_code").val("");
		$("#at_indp_code").val("");
		$("#at_number").val("");
		$("#at_manager").val("");
		$("#shop_name").val("");
		$("#outdepot_name").val("");
		$("#indepot_name").val("");
		THISPAGE.$_date.setValue(0);
		THISPAGE.$_ar_state.setValue(0);
		$("#begindate").val("");
		$("#enddate").val("");
	},
	reloadData:function(){
		var param=THISPAGE.buildParams();
		$("#grid").jqGrid('setGridParam',{datatype:"json",page:1,url:queryurl+'?'+param}).trigger("reloadGrid");
	},
	initEvent:function(){
		//查询
		$('#btn-search').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			THISPAGE.reloadData();
		});
		$('#btn_ok').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.SELECT)) {
				return ;
			}
			Public.hideConstion();
			THISPAGE.reloadData();
		});
		//新增
		$('#btn-add').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.INSERT)) {
				return ;
			}
			handle.operate('add');
		});
		$('#btn-del').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.DELETE)) {
				return ;
			}
			var rowId = $('#grid').jqGrid('getGridParam','selrow');
			if(rowId == null || rowId == ''){
				Public.tips({type: 1, content : "您未选择任何数据"});
				return;
			}
			var rowData =$("#grid").jqGrid("getRowData", rowId);
			if(rowData.at_ar_state != "未审核" && rowData.at_ar_state != "已退回"){
				Public.tips({type: 1, content : "单据已审核，不能删除"});
				return;
			}
			handle.del(rowId)
		});
		$('#btn_reset').on('click', function(e){
			e.preventDefault();
			THISPAGE.reset();
		});
		//导出
		$('#btn-export').on('click', function(e){
			e.preventDefault();
			if (!Business.verifyRight(_limitMenu,_menuParam.EXPORT)) {
				return ;
			};
			window.open(config.BASEPATH+'sort/allot/report?' + THISPAGE.buildParams());
		});
	}
}
THISPAGE.init();